package com.m.sms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.m.sms.annotation.SmsLimit;
import com.m.sms.response.SmsSendResponseBody;
import com.m.sms.response.SmsSendStatus;
import com.m.sms.enums.SmsStatusEnum;
import com.m.sms.exception.ValidateParamsException;
import com.m.sms.params.SmsSendRequestBody;
import com.m.sms.service.ISmsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.stream.Collectors;

/**
 * Description
 *
 * @Auther [li.wang@jsxfedu.com]
 * @Date 2025/3/20 13:17
 * @Version 1.0
 * @Copyright (c) 2022 京师讯飞
 */
@Slf4j
@AllArgsConstructor
public class AliSmsServiceImpl implements ISmsService {

    private com.aliyun.dysmsapi20170525.Client client;

    /**
     * 阿里云官方限制批量最大支持1000
     */
    private final static int MAX_MOBILE_LENGTH = 1000;

    @SmsLimit(value ="#smsSendRequestBody.mobile")
    @Override
    public SmsSendResponseBody sendSms(SmsSendRequestBody smsSendRequestBody) {

        if (StrUtil.isEmpty(smsSendRequestBody.getSignName())) {
            throw new ValidateParamsException("短信签名不能为空");
        }

        validateParams(smsSendRequestBody);

        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(smsSendRequestBody.getSignName())
                .setTemplateCode(smsSendRequestBody.getTelId());
        if (CollectionUtil.isNotEmpty(smsSendRequestBody.getMobileList())) {
            if (smsSendRequestBody.getMobileList().size() > MAX_MOBILE_LENGTH) {
                throw new ValidateParamsException(String.format("单次批量发送短信不能超过%s条", MAX_MOBILE_LENGTH));
            }
            sendSmsRequest.setPhoneNumbers(smsSendRequestBody.getMobileList().stream().collect(Collectors.joining(",")));
        } else {
            sendSmsRequest.setPhoneNumbers(smsSendRequestBody.getMobile());
        }
        if (CollectionUtil.isNotEmpty(smsSendRequestBody.getTelParam())) {
            sendSmsRequest.setTemplateParam(JSONObject.toJSONString(smsSendRequestBody.getTelParam()));
        }
        try {
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            log.info("发送阿里云短信结果：{}", JSONObject.toJSONString(response));
            SmsSendResponseBody smsSendResponseBody = new SmsSendResponseBody();
            smsSendResponseBody.setRequestId(response.getBody().getRequestId());
            smsSendResponseBody.setTotalCount(CollectionUtil.isNotEmpty(smsSendRequestBody.getMobileList()) ?
                    smsSendRequestBody.getMobileList().size() : 1);
            SmsSendStatus smsSendStatus = SmsSendStatus.builder()
                    .status(response.getBody().getCode().equals("OK") ? SmsStatusEnum.SUCCESS : SmsStatusEnum.FAIL)
                    .msg(response.getBody().getMessage()).build();
            smsSendResponseBody.getSendStatusList().add(smsSendStatus);
            return smsSendResponseBody;
        } catch (Exception e) {
            log.error("发送阿里云短信失败：{} \r\n{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
